package com.stedu.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.stedu.bean.Cars;
import com.stedu.bean.RespBean;
import com.stedu.exception.SteduException;
import com.stedu.service.impl.CarsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/admin/cars")
public class CarsController extends HttpServlet {
    @Autowired
    private CarsServiceImpl carsService;
    @Value("10")
    private  Integer pageSize;


    @PostMapping
   public RespBean insert(@Validated @RequestBody Cars cars) throws SteduException {

        if (carsService.insert(cars)) {
           return RespBean.ok("添加成功~~~");
        } else {
           return RespBean.error("添加失败，请重新添加");
        }

    }
    @DeleteMapping("/{cid}")
    public RespBean delete(@PathVariable("cid") int cid ) throws SteduException {
        //获取请求参数


        if (carsService.delete(cid)) {
           return  RespBean.ok("删除成功~~~");
        } else {
          return RespBean.error("删除失败，请重新删除");
        }
    }
   @PutMapping
    public RespBean update(@RequestBody Cars cars) throws SteduException {
       if (carsService.update(cars)) {
          return RespBean.ok("修改成功~~~");
       } else {
         return   RespBean.error("修改失败，请重新修改");
       }
    }
    @GetMapping("/{cid}")
    public RespBean selectByDid(@PathVariable("cid") int cid) {
        Cars c = carsService.selectBycid(cid);
         return RespBean.ok("", c);
    }
    @GetMapping
    public RespBean selectByCplate(Integer pageNum,String cplate,String cstate){

       if (pageNum == null){
           pageNum=1;
       }
        PageHelper.startPage(pageNum ,pageSize);
        List<Cars> carsList=carsService.selectBycplate(cplate,cstate);
        PageInfo<Cars>pageInfo=new PageInfo<>(carsList,5);
        return  RespBean.ok("查询成功", pageInfo);
    }
    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("车辆信息", "UTF-8").replaceAll("\\+", "%50");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Cars.class).sheet("模板").doWrite(carsService.selectBycplate(null,null));
    }

    @PostMapping("/upload")
    public RespBean upload(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), Cars.class, new PageReadListener<Cars>(dataList -> {
            for (Cars cars : dataList) {
                try {
                    carsService.insert(cars);
                } catch (SteduException e) {
                    // 处理异常
                    throw new RuntimeException(e.getMessage()); // 可以选择抛出 RuntimeException 或者记录错误
                }
            }
        })).sheet().doRead();
        return RespBean.ok("上传成功");
    }

}